-- SteamMachine
-- Created by cheny3 Oct/27/2016
-- 蒸汽机械

-- 初始化
function initSteamMachine(self)
    self.item:removeAllChildren();

    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 格子不可到达
            if not SteamMachineM.canHit(self.gridData:getPos()) then
                alert(getLocStr("grid_unreachable"));
                return;
            end

            local function okFunc()
                local pos = self.gridData:getPos();
                DungeonActionM.go("enter_steam_machine", pos);
            end

            local iconPath = getLevelItemIconPath(buildingInfo["icon"]);
            local dialog = buildingInfo["dialog"];
            local title = buildingInfo["title"];
            if 1 == self.gridData.broken then
                iconPath = getLevelItemIconPath(buildingInfo["icon2"]);
                dialog = buildingInfo["dialog2"];
                title = string.format(getLocStr("steam_wreckage"), title);
            end

            self:openBuildingView(okFunc, nil, dialog, nil, title, iconPath, nil, nil, {["scale"] = 0.5});
        end
    end

    local classId = self.gridData.class_id;
    local dbase = SteamMachineM.query(classId, "dbase");
    local offset = dbase["offset"] or {0, 0};

    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

    -- 如果破碎了
    if 1 == self.gridData.broken then
        iconPath = getLevelItemIconPath(buildingInfo["icon2"]);
    end

    -- 图标
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setPosition(cc.p(offset[1], offset[2]));

    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);

    local classId = self.gridData.class_id;
    local effectId = SteamMachineM.query(classId, "animation");
    if type(effectId) == "number" and 1 ~= self.gridData.broken then
        -- 创建模型
        local animation = createEffectAnim(effectId);
        -- 初始停在第一帧
        animation:gotoFrameAndPause(0);
        self.item.animation = animation;
        self.item:addChild(animation);
        self.icon:setOpacity(0);
        animation:setPosition(cc.p(20,-30));
    end
end
